var express = require('express');
var router = express.Router();

const { uploadFile } = require("../util/upload");
const moviesApi = require("../api/img");

//内置模块 原生模块
const path = require("path");
//fs 全称file-system
const fs = require("fs");
const util = require("util");
const unlink = util.promisify(fs.unlink);

//电影图片信息接口
router.post('/upload', async function (req, res, next) {
  const { data } = await uploadFile(req);
  console.log("chen" + data);
  data.token = req.headers["authorization"];
  const result = await moviesApi.addImg(data)
  res.send(result);
});

//电影海报接口
router.post('/poster', async function (req, res, next) {
  const { data } = await uploadFile(req);
  data.token = req.headers["authorization"];
  const result = await moviesApi.addPoster(data)
  res.send(result);
})

//删除电影图片信息接口
router.delete('/:_id', async function (req, res, next) {
  const { _id } = req.params;
  const { url } = req.body;
  const fileUrl = path.join(path.resolve(__dirname, "../public"), url);
  //删除文件
  await unlink(fileUrl);
  const data = await moviesApi.removeImg({ _id, url })
  res.send(data)
});

module.exports = router;